package com.topvision.face.util;

import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class SSLRequestUtil {
//	 /**
//     * Post请求连接Https服务
//     * @param serverURL  请求地址
//     * @param jsonStr    请求报文
//     * @return
//     * @throws Exception
//     */
//    public static synchronized String doHttpsPost(String serverURL, String jsonStr)throws Exception {
//        // 参数
//        HttpParams httpParameters = new BasicHttpParams();
//        // 设置连接超时
//        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
//        // 设置socket超时
//        HttpConnectionParams.setSoTimeout(httpParameters, 3000);
//        // 获取HttpClient对象 （认证）
//        HttpClient hc = initHttpClient(httpParameters);
//        HttpPost post = new HttpPost(serverURL);
//        // 发送数据类型
//        post.addHeader("Content-Type", "application/json;charset=utf-8");
//        // 接受数据类型
//        post.addHeader("Accept", "application/json");
//        // 请求报文
//        StringEntity entity = new StringEntity(jsonStr, "UTF-8");
//        post.setEntity(entity);
//        post.setParams(httpParameters);
//        HttpResponse response = null;
//        try {
//            response = hc.execute(post);
//        } catch (UnknownHostException e) {
//            throw new Exception("Unable to access " + e.getLocalizedMessage());
//        } catch (SocketException e) {
//            e.printStackTrace();
//        }
//        int sCode = response.getStatusLine().getStatusCode();
//        if (sCode == HttpStatus.SC_OK) {
//            return EntityUtils.toString(response.getEntity());
//        } else
//            throw new Exception("StatusCode is " + sCode);
//    }
//
//    private static HttpClient client = null;
//    /**
//     * 初始化HttpClient对象
//     * @param params
//     * @return
//     */
//    public static synchronized HttpClient initHttpClient(HttpParams params) {
//        if(client == null){
//            try {
//                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//                trustStore.load(null, null);
//                
//                SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);
//                //允许所有主机的验证
//                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//                
//                HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//                HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
//                // 设置http和https支持
//                SchemeRegistry registry = new SchemeRegistry();
//                registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
//                registry.register(new Scheme("https", sf, 443));
//                
//                ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
//                
//                return new DefaultHttpClient(ccm, params);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return new DefaultHttpClient(params);
//            }
//        }
//        return client;
//    }
//
//   public static class SSLSocketFactoryImp extends SSLSocketFactory {
//        final SSLContext sslContext = SSLContext.getInstance("TLS");
//
//        public SSLSocketFactoryImp(KeyStore truststore)
//                throws NoSuchAlgorithmException, KeyManagementException,
//                KeyStoreException, UnrecoverableKeyException {
//            super(truststore);
//
//            TrustManager tm = new X509TrustManager() {
//                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                    return null;
//                }
//
//                @Override
//                public void checkClientTrusted(
//                        java.security.cert.X509Certificate[] chain,
//                        String authType)
//                        throws java.security.cert.CertificateException {
//                }
//
//                @Override
//                public void checkServerTrusted(
//                        java.security.cert.X509Certificate[] chain,
//                        String authType)
//                        throws java.security.cert.CertificateException {
//                }
//            };
//            sslContext.init(null, new TrustManager[] { tm }, null);
//        }
//
//        @Override
//        public Socket createSocket(Socket socket, String host, int port,
//                boolean autoClose) throws IOException, UnknownHostException {
//            return sslContext.getSocketFactory().createSocket(socket, host,
//                    port, autoClose);
//        }
//
//        @Override
//        public Socket createSocket() throws IOException {
//            return sslContext.getSocketFactory().createSocket();
//        }
//    }
   
   
	 public static String CONTENT_TYPE = "multipart/form-data"; // 内容类型
     static String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
   /**
    * 初始化http请求参数
    */
   public static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
           throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
       TrustManager[] tm = {new CustomX509TrustManager()};
       SSLContext sslContext = SSLContext.getInstance("TLSv1");
       sslContext.init(null, tm, new java.security.SecureRandom());
       // 从上述SSLContext对象中得到SSLSocketFactory对象
       SSLSocketFactory ssf  = sslContext.getSocketFactory();
       URL _url = new URL(url);
       HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
       // 连接超时
       http.setConnectTimeout(25000);
       // 读取超时 --服务器响应比较慢，增大时间
       http.setReadTimeout(25000);
       http.setRequestMethod(method);
       http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
       http.setRequestProperty("User-Agent",
               "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
       if (null != headers && !headers.isEmpty()) {
           for (Map.Entry<String, String> entry : headers.entrySet()) {
               http.setRequestProperty(entry.getKey(), entry.getValue());
           }
       }
       http.setSSLSocketFactory(ssf);
       http.setDoOutput(true);
       http.setDoInput(true);
       http.setRequestProperty("Charset", "utf-8"); // 设置编码
       http.setRequestProperty("connection", "keep-alive");
       http.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);
       http.connect();
       return http;
   }
   
   
// 证书管理
static class CustomX509TrustManager implements X509TrustManager {

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
}

}
